package server.main.config.springsecurity.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import server.main.pojo.Account;
import server.main.service.AccountService;
import server.main.service.AfterService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    AccountService accountService;

    @Autowired
    AfterService afterService;



    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","登录成功");


        Account user = accountService.getOne(
                new LambdaQueryWrapper<Account>().eq(Account::getUsername, httpServletRequest.getParameter("username"))
        );


        Account returnuser = new Account();
        returnuser.setJobnum(user.getJobnum());
        returnuser.setUsername(user.getUsername());
        returnuser.setPersonalization(user.getPersonalization());
        //设置返回的前端界面的信息
        Map<String, List<String>> urls = afterService.getMenu(httpServletRequest.getParameter("username"));
        user.setMenuUrls(urls.toString());


        returnuser.setMenuUrls(accountService.getMenuJsonString(user.getJobnum()));
        map.put("user",returnuser);


//        httpServletRequest.getSession().setAttribute("username",authentication.getName());

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(map));
        out.flush();
        out.close();
    }
}
